/**
 * recordAsset弹窗管理 Hook
 * 处理全局弹窗事件和状态管理
 */

import { useState, useEffect } from 'react';

interface RecordAssetModalState {
  isOpen: boolean;
  modalId: string | null;
  dataHash: string;
  defaultDataDetails: string;
  onConfirm: ((dataDetails: string) => void) | null;
  onCancel: (() => void) | null;
}

export function useRecordAssetModal() {
  const [modalState, setModalState] = useState<RecordAssetModalState>({
    isOpen: false,
    modalId: null,
    dataHash: '',
    defaultDataDetails: '',
    onConfirm: null,
    onCancel: null
  });

  useEffect(() => {
    const handleShowModal = (event: CustomEvent) => {
      const { modalId, dataHash, defaultDataDetails, onConfirm, onCancel } = event.detail;
      
      setModalState({
        isOpen: true,
        modalId,
        dataHash,
        defaultDataDetails,
        onConfirm,
        onCancel
      });
    };

    globalThis.addEventListener('showRecordAssetModal', handleShowModal as EventListener);

    return () => {
      globalThis.removeEventListener('showRecordAssetModal', handleShowModal as EventListener);
    };
  }, []);

  const closeModal = () => {
    if (modalState.onCancel) {
      modalState.onCancel();
    }
    setModalState(prev => ({ ...prev, isOpen: false }));
  };

  const confirmModal = (dataDetails: string) => {
    if (modalState.onConfirm) {
      modalState.onConfirm(dataDetails);
    }
    setModalState(prev => ({ ...prev, isOpen: false }));
  };

  return {
    modalState,
    closeModal,
    confirmModal
  };
}
